package com.itheima.easy.handler.aliyun;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.*;
import com.itheima.easy.config.alipay.AliPayConfig;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.enums.TradeEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.CommonPayHandler;
import com.itheima.easy.utils.BeanConv;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.utils.SnowflakeIdWorker;
import com.itheima.easy.vo.RefundRecordVo;
import com.itheima.easy.vo.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName AliCommonPayHandler.java
 * @Description 阿里支付基础支付
 */
@Slf4j
@Service
public class AliCommonPayHandler implements CommonPayHandler {

    @Autowired
    AliPayConfig aliPayConfig;

    @Override
    public TradeVo queryTrade(TradeVo tradeVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            //4、调用支付宝API：通用查询支付情况
            AlipayTradeQueryResponse queryResponse = Factory.Payment.Common()
                    .query(String.valueOf(tradeVo.getTradeOrderNo()));
            //5、判断响应是否成功
            boolean success = ResponseChecker.success(queryResponse);
            //6、响应成功，分析交易状态
            boolean flag = true;
            if (success&&!EmptyUtil.isNullOrEmpty(queryResponse.getTradeStatus())){
                switch (queryResponse.getTradeStatus()){
                    //支付取消：TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）
                    case TradeConstant.ALI_TRADE_CLOSED:
                        tradeVo.setTradeState(TradeConstant.TRADE_CLOSED);break;
                    //支付成功：TRADE_SUCCESS（交易支付成功）
                    case TradeConstant.ALI_TRADE_SUCCESS:
                        tradeVo.setTradeState(TradeConstant.TRADE_SUCCESS);break;
                    //支付成功：TRADE_FINISHED（交易结束，不可退款）
                    case TradeConstant.ALI_TRADE_FINISHED:
                        tradeVo.setTradeState(TradeConstant.TRADE_SUCCESS);break;
                    //非最终状态不处理，当前交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）不处理
                    default:
                        flag = false;break;
                }
                //7、修改交易单状态
                if (flag){
                    tradeVo.setResultCode(queryResponse.getSubCode());
                    tradeVo.setResultMsg(queryResponse.getSubMsg());
                    tradeVo.setResultJson(JSONObject.toJSONString(queryResponse));
                    return tradeVo;
                }else {
                    log.info("查询支付宝交易单：{},结果：{}", tradeVo.getTradeOrderNo(),queryResponse.getTradeStatus());
                }
            }else {
                throw new RuntimeException("网关：查询支付宝统一下单失败！");
            }
        } catch (Exception e) {
            log.warn("查询支付宝统一下单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询支付宝统一下单失败！");
        }
        return tradeVo;
    }

    @Override
    public TradeVo refundTrade(TradeVo tradeVo) {
        //1、生成退款请求编号
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
        tradeVo.setOutRequestNo(String.valueOf(snowflakeIdWorker.nextId()));
        //2、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //4、使用配置
        Factory.setOptions(config);
        //5、调用退款接口
        try {
            AlipayTradeRefundResponse refundResponse = Factory.Payment.Common()
                .optional("out_request_no", tradeVo.getOutRequestNo())
                .refund(String.valueOf(tradeVo.getTradeOrderNo()),
                        String.valueOf(tradeVo.getOperTionRefund()));
            //6、判断响应是否成功
            boolean success = ResponseChecker.success(refundResponse);
            if (success&&String.valueOf(tradeVo.getTradeOrderNo()).equals(refundResponse.getOutTradeNo())){
                //7、保存交易单信息
                tradeVo.setIsRefund(SuperConstant.YES);
                tradeVo.setRefund(tradeVo.getRefund().add(tradeVo.getOperTionRefund()));
                //8、保存退款单信息
                RefundRecordVo refundRecordVo = RefundRecordVo.builder()
                    .enterpriseId(tradeVo.getEnterpriseId())
                    .storeId(tradeVo.getStoreId())
                    .refundNo(tradeVo.getOutRequestNo())
                    .refundAmount(tradeVo.getOperTionRefund())
                    .refundCode(refundResponse.getSubCode())
                    .refundMsg(refundResponse.getSubMsg())
                    .productOrderNo(tradeVo.getProductOrderNo())
                    .tradeChannel(tradeVo.getTradeChannel())
                    .tradeOrderNo(tradeVo.getTradeOrderNo())
                    .refundStatus(success?TradeConstant.REFUND_STATUS_SENDING:TradeConstant.REFUND_STATUS_FAIL)
                    .memo("退款："+tradeVo.getMemo())
                    .build();
            }else {
                log.error("网关：支付宝统一下单退款：{},结果：{}", tradeVo.getTradeOrderNo(),
                        JSONObject.toJSONString(refundResponse));
                throw new RuntimeException("网关：支付宝统一下单退款失败");
            }
        } catch (Exception e) {
            log.error("支付宝统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradeEnum.TRAD_REFUND_FAIL);
        }
        return BeanConv.toBean(tradeVo, TradeVo.class);
    }

    @Override
    public RefundRecordVo queryRefundTrade(RefundRecordVo refundRecordVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            AlipayTradeFastpayRefundQueryResponse refundQueryResponse =
                Factory.Payment.Common().queryRefund(
                    String.valueOf(refundRecordVo.getTradeOrderNo()),
                    refundRecordVo.getRefundNo());
            //4、判断响应是否成功
            boolean success = ResponseChecker.success(refundQueryResponse);
            //5、查询出的退款状态
            String refundStatus = refundQueryResponse.getRefundStatus();
            if (success&&TradeConstant.REFUND_SUCCESS.equals(refundStatus)){
                refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_SUCCESS);
                refundRecordVo.setRefundCode(refundQueryResponse.getSubCode());
                refundRecordVo.setRefundMsg(refundQueryResponse.getSubMsg());
            }else {
                log.error("网关：查询支付宝统一下单退款：{},结果：{}", refundRecordVo.getTradeOrderNo(),
                    JSONObject.toJSONString(refundQueryResponse));
                throw new RuntimeException("网关：查询支付宝统一下单退款失败！");
            }
        } catch (Exception e) {
            log.warn("查询支付宝统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询支付宝统一下单退款失败！");
        }
        return refundRecordVo;
    }

    @Override
    public TradeVo closeTrade(TradeVo tradeVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            //4、调用三方API关闭订单
            AlipayTradeCloseResponse closeResponse = Factory.Payment.Common()
                .close(String.valueOf(tradeVo.getTradeOrderNo()));
            //5、关闭订单受理情况
            boolean success = ResponseChecker.success(closeResponse);
            if (success&&tradeVo.getTradeOrderNo().equals(closeResponse.getOutTradeNo())){
                tradeVo.setTradeState(TradeConstant.TRADE_CLOSED);
                return tradeVo;
            }else {
                log.error("网关：支付宝关闭订单：{},结果：{}", tradeVo.getTradeOrderNo(),
                    JSONObject.toJSONString(closeResponse));
                throw  new RuntimeException("网关：支付宝关闭订单失败!");
            }
        } catch (Exception e) {
            log.warn("关闭订单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw  new ProjectException(TradeEnum.TRAD_CLOSE_FAIL);
        }
    }

    @Override
    public TradeVo downLoadBill(TradeVo tradeVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse billDownloadurlQueryResponse = Factory.Payment.Common()
                .downloadBill(tradeVo.getBillType(), DateUtil.formatDate(tradeVo.getBillDate()));
            //4、请求下载受理情况
            boolean success = ResponseChecker.success(billDownloadurlQueryResponse);
            if (success){
                String billDownloadUrl = billDownloadurlQueryResponse.getBillDownloadUrl();
                tradeVo.setBillDownloadUrl(billDownloadUrl);
            }else {
                log.warn("网关：支付宝下载订单类型：{},时间：{},结果：{}", tradeVo.getBillType(),tradeVo.getBillDate(),
                        JSONObject.toJSONString(billDownloadurlQueryResponse));
                throw new RuntimeException("网关：支付宝下载订单失败！");
            }
        } catch (Exception e) {
            log.warn("支付宝下载订单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw  new RuntimeException("支付宝下载订单失败！");
        }
        return tradeVo;
    }

}
